package com.demo.java;

import cn.hutool.log.StaticLog;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) {

        testNewScheduledThreadPool();



    }

    public static void testNewScheduledThreadPool(){
        try {
            long mainThreadId = Thread.currentThread().getId();
            StaticLog.info("主线程ID={}",mainThreadId);
            ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
            ScheduledFuture<?> future1 = scheduledExecutorService.schedule(new Runnable() {
                @Override
                public void run() {
                    long threadId = Thread.currentThread().getId();
                    StaticLog.info("任务1，5秒延迟，线程ID={}",threadId);
                }
            },5,TimeUnit.SECONDS);
            StaticLog.info("任务1已提交");
            future1.get();
            StaticLog.info("任务1已执行完毕");

            final AtomicInteger count = new AtomicInteger(0);
            final String jobKey = "jobKey";
            final Map<String, Future<?>> futureMap = new HashMap<>();
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            Future<?> future2 = scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
                @Override
                public void run() {
                    int countVal = count.getAndIncrement();
                    long threadId = Thread.currentThread().getId();
                    StaticLog.info("任务2，3秒延迟，每秒执行一次，执行第{}次，线程ID={}",countVal,threadId);
                    if (countVal >= 4) {
                        Future<?> future = futureMap.get(jobKey);
                        if (future != null){
                            future.cancel(true);
                            countDownLatch.countDown();
                        }
                    }
                }
            }, 3, 1, TimeUnit.SECONDS);
            futureMap.put(jobKey, future2);

            countDownLatch.await();
            scheduledExecutorService.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void testNewCachedThreadPool(){
        long mainThreadId = Thread.currentThread().getId();
        StaticLog.info("主线程ID={}",mainThreadId);
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                long threadId = Thread.currentThread().getId();
                StaticLog.info("测试线程ID={}",threadId);
            }
        });
    }
}
